﻿using System;
using System.Diagnostics.Contracts;
using System.Linq;
using Adalbertus.BudgetPlanner.Domain;
using Adalbertus.BudgetPlanner.Services.Dto;

namespace Adalbertus.BudgetPlanner.Services.Extensions
{
    public static class DomainConvertExtensions
    {
        public static IEntity ToDomain(this IDto dto)
        {
            Contract.Requires<ArgumentNullException>(dto != null);
            Contract.Ensures(Contract.Result<IEntity>() != null);

            switch (dto.GetType().Name)
            {
                case "ExternalSourceDto":
                    return ((ExternalSourceDto)dto).ToDomain();
                case "CashFlowTypeDto":
                    return ((CashFlowTypeDto)dto).ToDomain();
                default:
                    throw new InvalidOperationException(
                        string.Format("Nie można odnaleźć konwertera z dto do encji dla dto {0}",
                                      dto.GetType().Name));
            }

        }

        public static ExternalSource ToDomain(this ExternalSourceDto dto)
        {
            Contract.Requires<ArgumentNullException>(dto != null);
            Contract.Ensures(Contract.Result<ExternalSource>() != null);

            ExternalSource externalSource = new ExternalSource
            {
                Id = dto.Id,
                IsUnlimited = dto.IsUnlimited,
                Name = dto.Name
            };
            externalSource.Items =
                dto.Items.Select(i => new ExternalSourceItem
                {
                    Id = i.Id,
                    Date = i.Date,
                    Description = i.Description,
                    IsFrozen = i.IsFrozen,
                    Value = i.Value
                }).ToList();
            return externalSource;
        }


        public static CashFlowType ToDomain(this CashFlowTypeDto dto)
        {
            Contract.Requires<ArgumentNullException>(dto != null);
            Contract.Ensures(Contract.Result<CashFlowType>() != null);

            CashFlowType cashFlowType = new CashFlowType
            {
                Id = dto.Id,
                Name = dto.Name,
                Description = dto.Description
            };
            if (dto.ExternalSource != null)
            {
                cashFlowType.ExternalSource = dto.ExternalSource.ToDomain();
            }
            return cashFlowType;
        }
    }
}
